package com.shensi.appCollect.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shensi.appCollect.pojo.CouponTemplate;
import com.shensi.appCollect.pojo.CouponUser;
import com.shensi.appCollect.dao.*;
import com.shensi.appCollect.pojo.*;
import com.shensi.appCollect.pojo.dto.CancelCouponDto;
import com.shensi.appCollect.pojo.vo.CouponInfoVO;
import com.shensi.appCollect.service.*;
import com.shensi.appCollect.utils.CodeMsg;
import com.shensi.appCollect.utils.ResultData;
import com.shensi.appCollect.utils.exception.CustomException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author PC
 * @description 针对表【coupon_write_off_records(优惠券核销记录表)】的数据库操作Service实现
 * @createDate 2023-10-17 20:16:44
 */
@Service
@Slf4j
public class CouponWriteOffRecordsServiceImpl extends ServiceImpl<CouponWriteOffRecordsMapper, CouponWriteOffRecords>
        implements CouponWriteOffRecordsService {


    @Resource
    private CouponService couponService;

    @Resource
    private PosMachineService posMachineService;

    @Resource
    private EnterpriseService enterpriseService;

    @Resource
    private CouponWriteOffRecordsMapper couponWriteOffRecordsSerivce;

    @Resource
    private CouponWriteOffRecordsMapper couponWriteOffRecordsMapper;

    @Override
    @SneakyThrows
    @Transactional
    public ResultData<?> cancelCoupon(CancelCouponDto cancelCouponDto) {

        //根据券码获取优惠券信息
        log.info("优惠券券码：{}", cancelCouponDto.getCouponNo());
        List<CouponUser> couponUsersInfo = couponService.selectUserAllCoupons(CouponUser.builder().couponNo(cancelCouponDto.getCouponNo()).build());
        //获取核销人员信息
        SysUser sysUser = posMachineService.selectUserByUserId(cancelCouponDto.getOilPersonnelId());

        if (CollectionUtil.isNotEmpty(couponUsersInfo) && ObjectUtils.isNotEmpty(sysUser)) {
            CouponUser couponUser = couponUsersInfo.get(0);
            cancelCouponType(couponUser, sysUser, cancelCouponDto);
        }

        return ResultData.error(CodeMsg.COUPON_VERIFICATION_ERROR, "无此优惠券");
    }

    @Override
    public ResultData<CouponInfoVO> getIfCancelCouponSuccess(String couponNo) {
        List<CouponUser> couponUsersInfo = couponService.selectUserAllCoupons(CouponUser.builder().couponNo(couponNo).build());
        if (CollectionUtil.isEmpty(couponUsersInfo)){
            return ResultData.error(CodeMsg.THERE_IS_NO_SUCH_WRITE_OFF);
        }
        CouponUser couponUser = couponUsersInfo.get(0);
        String couponType = couponUser.getCouponTemplateInfo().getCouponType();
        String couponEffectiveTime = couponUser.getCouponEffectiveTime();
        String oils = couponUser.getOils();
        String couponStaNames = couponUser.getCouponStaNames();
        String couponIsUsed = couponUser.getCouponIsUsed();
        String couponRemark = couponUser.getCouponTemplateInfo().getCouponRemark();
        String writeOffTime = null;
        if (couponIsUsed.equals("1")){
            Date cancelCouponTime = couponWriteOffRecordsMapper.getCancelCouponTime(couponNo);
            if (null != cancelCouponTime){
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                writeOffTime = sdf1.format(cancelCouponTime);
            }
        }
        CouponInfoVO couponInfoVO = CouponInfoVO.builder().
                couponEffectiveTime(couponEffectiveTime).
                couponType(couponType).
                couponStaNames(couponStaNames).
                oils(oils)
                .writeOffTime(writeOffTime)
                .couponIsUsed(couponIsUsed)
                .couponRemark(couponRemark).build();
        return ResultData.success(couponInfoVO);
    }



    //根据优惠券类型进行核销
    private void cancelCouponType(CouponUser couponUser, SysUser sysUser, CancelCouponDto ccd) throws Exception {
        switch (couponUser.getCouponTemplateInfo().getCouponType()) {
            //现金券
            case "1":
                break;
            //折扣券
            case "2":
                break;
            //兑换券
            case "3":
                if ("1".equals(sysUser.getEnterpriseId())) {
                    if ("0".equals(sysUser.getStatus())) {
                        //获取该兑换券的核销站点
                        List<CouponUser> couponUsersInfo = couponService.selectUserAllCoupons(CouponUser.builder().couponNo(ccd.getCouponNo()).build());
                        if (CollectionUtil.isNotEmpty(couponUsersInfo)) {
                            if (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(couponUsersInfo.get(0).getCouponEffectiveTime()).after(new Date())) {
                                if ("0".equals(couponUsersInfo.get(0).getCouponIsUsed())) {
                                    CouponTemplate couponTemplateInfo = couponUsersInfo.get(0).getCouponTemplateInfo();
                                    if (null != couponTemplateInfo && "3".equals(couponTemplateInfo.getCouponType())) {
                                        if ("1".equals(couponTemplateInfo.getCouponTemplateStatus())) {
                                            boolean boo = false;
                                            if (StringUtils.isNotBlank(couponTemplateInfo.getVerification())) {
                                                if (Arrays.asList(couponTemplateInfo.getVerification().split(",")).contains(sysUser.getStationId()))
                                                    boo = true;
                                            }
                                            if (sysUser.getEnterpriseId().equals(couponUsersInfo.get(0).getEnterpriseId().toString()))
                                                boo = true;
                                            if (boo) {
                                                //更新用户优惠券信息
                                                couponService.updateCouponUser(CouponUser.builder().couponNo(ccd.getCouponNo()).verificationTime(new Date()).couponIsUsed("1").verificationUserAccount(sysUser.getUserName()).verificationUserPhone(sysUser.getPhonenumber()).build());
                                                //更新优惠券使用模板数量
                                                couponService.updateCouponTemplate(CouponTemplate.builder().couponTemplateId(couponTemplateInfo.getCouponTemplateId()).useCouponNum(couponTemplateInfo.getUseCouponNum() + 1).build());

                                            } else {
                                                throw new CustomException(CodeMsg.SITE_AND_PERSONNEL_ARE_INCONSISTENT);
                                            }
                                        } else {
                                            throw new CustomException(CodeMsg.THIS_COUPON_IS_INVALID);
                                        }
                                    } else {
                                        throw new CustomException(CodeMsg.NOT_CERTIFICATE);
                                    }
                                } else {
                                    throw new CustomException(CodeMsg.COUPON_VERIFICATION_USED);
                                }
                            } else {
                                throw new CustomException(CodeMsg.ERROR_COUPON_DATE);
                            }
                        } else {
                            throw new CustomException(CodeMsg.THERE_IS_NO_SUCH_WRITE_OFF);
                        }
                    } else {
                        throw new CustomException(CodeMsg.ACCOUNT_DISABLE);
                    }
                } else {
                    throw new CustomException(CodeMsg.NOT_COUPON_VERIFICATION_USER);
                }
                break;
            //洗车券
            case "4":
                log.info("查询油品信息入参：{}", ccd.getOilName());
                Oil oil = enterpriseService.selectOilByOilId(Integer.valueOf(ccd.getOilName()));
                log.info("查询油品信息出参：{}", oil);
                String enterpriseId = sysUser.getEnterpriseId();
                String couponUserEnterpriseId = couponUser.getEnterpriseId().toString();
                if (!enterpriseId.equals(couponUserEnterpriseId)) {
                    throw new CustomException(CodeMsg.CAN_BE_HERE);
                }
                String couponStaNames = couponUser.getCouponStaNames();
                Station station = enterpriseService.selectStationById(Integer.valueOf(sysUser.getStationId()));
                String stationName = station.getStationName();
                List<String> nameList = Arrays.asList(couponStaNames.split(","));

                if (!nameList.contains(stationName)) {
                    throw new CustomException(CodeMsg.CAN_BE_HERE);
                }
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if (simpleDateFormat.parse(couponUser.getCouponEffectiveTime()).after(new Date())) {

                    //状态
                    if ("0".equals(couponUser.getCouponIsUsed())) {

                        if (!oil.getOilType().equals("服务")) {
                            throw new CustomException(CodeMsg.NOT_A_CAR_WASH);
                        }
                        CouponTemplate couponTemplateInfo = couponUser.getCouponTemplateInfo();

                        String effectiveTimeType = couponTemplateInfo.getEffectiveTimeType();
                        if (null != effectiveTimeType && effectiveTimeType.equals("1")) {
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String effectiveTimeEnd = sdf.format(couponTemplateInfo.getEffectiveTimeEnd());
                            String effectiveTimeStart = sdf.format(couponTemplateInfo.getEffectiveTimeStart());
                            if (simpleDateFormat.parse(effectiveTimeStart).after(new Date())) {
                                throw new CustomException(CodeMsg.TIME_IS_NOT_UP);
                            }

                        }

                        //判断是否洗车券及状态
                        if (ObjectUtils.isNotEmpty(couponTemplateInfo) && "4".equals(couponTemplateInfo.getCouponType()) && "1".equals(couponTemplateInfo.getCouponTemplateStatus())) {
                            if (null == couponTemplateInfo.getVerification() || Arrays.asList(couponTemplateInfo.getVerification().split(",")).contains(sysUser.getStationId())) {
                                //更新用户优惠券信息
                                couponService.updateCouponUser(CouponUser.builder().couponNo(ccd.getCouponNo()).verificationTime(new Date()).couponIsUsed("1").verificationUserAccount(sysUser.getUserName()).verificationUserPhone(sysUser.getPhonenumber()).build());
                                //更新优惠券使用模板数量
                                couponService.updateCouponTemplate(CouponTemplate.builder().couponTemplateId(couponTemplateInfo.getCouponTemplateId()).useCouponNum(couponTemplateInfo.getUseCouponNum() + 1).build());
                                //记录在优惠券核销表
                                addCancelCouponRecord(couponUser, ccd);
                            }
                        }
                    }
                    break;
                }
        }
    }


    //优惠券核销记录表
    private Integer addCancelCouponRecord(CouponUser couponUser, CancelCouponDto ccd) {

        CouponWriteOffRecords couponWriteOffRecords = new CouponWriteOffRecords();
        couponWriteOffRecords.setCouponNo(couponUser.getCouponNo());
        couponWriteOffRecords.setAmt(couponUser.getCouponTemplateInfo().getCouponAmt());
        couponWriteOffRecords.setCreatedDate(new Date());
        couponWriteOffRecords.setEnterpriseId(Long.valueOf(couponUser.getEnterpriseId()));
        couponWriteOffRecords.setStationId(Long.valueOf(ccd.getStationId()));
        couponWriteOffRecords.setCouponType(Integer.valueOf(couponUser.getCouponTemplateInfo().getCouponType()));
        couponWriteOffRecords.setWriteOffPersonnelId(Integer.valueOf(ccd.getOilPersonnelId()));
        return couponWriteOffRecordsSerivce.insert(couponWriteOffRecords);
    }
}




